import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bmflocation/flutter_bmflocation.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:zrjz/comm/utils/log_utils.dart';
import 'package:zrjz/comm/utils/util.dart';
import 'package:zrjz/comm/widget/dialog/permission_desc_dialog.dart';

/*
    百度地图获取经纬度的封装
    1.权限的校验与定位权限的申请，并提示详情描述弹窗
    2.调用百度地图的SDK分别获取Ios与Android的定位，并封装到Rx对象 loationResult 可以响应式刷新
 */
class LocationUtil {
  static final LocationUtil _locationUtil = LocationUtil._internal();
  final LocationFlutterPlugin _myLocPlugin = LocationFlutterPlugin();

  //百度定位的获取到定位成功的结果
  Rx<BaiduLocation> loationResult = BaiduLocation().obs;
  BaiduLocation get getBaiduLocation => loationResult.value;

  bool _suc = false;

  //构造函数私有化
  LocationUtil._internal();

  //工厂构造函数
  factory LocationUtil() {
    return _locationUtil;
  }

  //初始化百度定位
  void initBaiduLocation() {
    /// 动态申请定位权限
    // requestPermission();
    // 设置是否隐私政策
    _myLocPlugin.setAgreePrivacy(true);

    if (Platform.isIOS) {
      /// 设置ios端ak, android端ak可以直接在清单文件中配置
      // myLocPlugin.authAK('yFDD3IlfSk2xTdQ0G41MjRnzd5gUVG1C');
      // _myLocPlugin.authAK('XOa3FnUtuQjT37LkTHgOBwaHGidYcuxl');
      _myLocPlugin.authAK('xxxxxxxx12345678');
      // BMFMapSDK.setApiKeyAndCoordType(
      //     'yFDD3IlfSk2xTdQ0G41MjRnzd5gUVG1C', BMF_COORD_TYPE.BD09LL);
    } else if (Platform.isAndroid) {
      // Android 目前不支持接口设置Apikey,
      // 请在主工程的Manifest文件里设置，详细配置方法请参考官网(https://lbsyun.baidu.com/)demo
      // BMFMapSDK.setCoordType(BMF_COORD_TYPE.BD09LL);
    }

    /// iOS端鉴权结果
    _myLocPlugin.getApiKeyCallback(callback: (String result) {
      String str = result;
      print('鉴权结果：' + str);
    });
  }

  /// 申请定位权限
  /// 授予定位权限返回true， 否则返回false
  Future<bool> checkLocationPermission() async {
    //获取当前的权限
    var status = await Permission.location.status;

    if (status == PermissionStatus.granted) {
      //已经授权
      return true;
    } else {
      //未授权则发起一次申请，弹出权限申请的同时展示权限描述
      _showPermissionDialog("“Room”想访问您的定位权限获取您的位置来推荐附近的工作");
      status = await Permission.location.request();
      SmartDialog.dismiss(status: SmartStatus.dialog, tag: "permission");

      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }

  //顶部展示权限声明详情弹窗
  void _showPermissionDialog(String desc) {
    SmartDialog.show(
      useAnimation: false,
      clickMaskDismiss: false,
      backDismiss: true,
      keepSingle: false,
      bindPage: true,
      tag: "permission",
      maskColor: Colors.transparent,
      builder: (context) => PermissionDescDialog(desc),
    );
  }

  //初始化定位
  void initLocation(ValueChanged<BaiduLocation> locationCallBack) {
    ///单次定位时如果是安卓可以在内部进行判断调用连续定位
    if (Platform.isIOS) {
      ///接受定位回调
      _myLocPlugin.singleLocationCallback(callback: (BaiduLocation result) {
        loationResult.value = result;
        _locationFinish();

        locationCallBack(result);
      });
    } else if (Platform.isAndroid) {
      ///接受定位回调
      _myLocPlugin.seriesLocationCallback(callback: (BaiduLocation result) {
        loationResult.value = result;
        _locationFinish();

        locationCallBack(result);

        _myLocPlugin.stopLocation();
      });
    }
  }

  void _locationAction() async {
    /// 设置android端和ios端定位参数
    /// android 端设置定位参数
    /// ios 端设置定位参数
    Map iosMap = _initIOSOptions().getMap();
    Map androidMap = _initAndroidOptions().getMap();

    _suc = await _myLocPlugin.prepareLoc(androidMap, iosMap);
    Log.d('设置定位参数：$iosMap');
  }

  /// 设置地图参数
  BaiduLocationAndroidOption _initAndroidOptions() {
    BaiduLocationAndroidOption options = BaiduLocationAndroidOption(
        // coorType: 'bd09ll',
        locationMode: BMFLocationMode.hightAccuracy,
        isNeedAddress: true,
        isNeedAltitude: true,
        isNeedLocationPoiList: true,
        isNeedNewVersionRgc: true,
        isNeedLocationDescribe: true,
        openGps: true,
        locationPurpose: BMFLocationPurpose.sport,
        coordType: BMFLocationCoordType.gcj02);
    return options;
  }

  BaiduLocationIOSOption _initIOSOptions() {
    BaiduLocationIOSOption options = BaiduLocationIOSOption(
        coordType: BMFLocationCoordType.gcj02,
        // BMKLocationCoordinateType: 'BMKLocationCoordinateTypeBMK09LL',
        desiredAccuracy: BMFDesiredAccuracy.best);
    return options;
  }

  /// 启动定位
  Future<void> startLocation() async {
    //设置定位参数
    _locationAction();

    if (Platform.isIOS) {
      _suc = await _myLocPlugin.singleLocation({'isReGeocode': true, 'isNetworkState': true});
      Log.d('开始单次定位：$_suc');
    } else if (Platform.isAndroid) {
      _suc = await _myLocPlugin.startLocation();
    }
  }

  //当前是否已经有成功结果了，return true 为成功  return false 为失败
  bool isLocationSuccess(){
   return !Utils.isEmpty(getBaiduLocation.locTime);
  }

  void _locationFinish() {
    if (isLocationSuccess()) {

      Log.d("经纬度  lat: ${loationResult.value.latitude.toString()} - lon: ${loationResult.value.longitude.toString()}  "
          "Code: ${loationResult.value.adCode}  城市: ${loationResult.value.city}  区县：${loationResult.value.district}");
    }
  }


}
